package com.luboyan.CBillbill.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * Json信息转换配置类（fastjson）
 */
@Configuration
public class JsonHttpMessageConverterConfig {

    @Bean
    @Primary
    public HttpMessageConverters fastJsonHttpMessageConverters(){
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter =
                new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig(); //生成fastjson的配置清单
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); //设置时间的格式

        // 定义 ValueFilter 来将 Long 类型自动转换为 String
        ValueFilter longToStringFilter = (object, name, value) -> {
            if (value instanceof Long) {
                return String.valueOf(value); // 将 Long 转换为 String
            }
            return value; // 其他类型不做处理
        };
        fastJsonConfig.setSerializeFilters(longToStringFilter); // 设置自定义的序列化过滤器

        fastJsonConfig.setSerializerFeatures( //对数据的序列化设置
                SerializerFeature.PrettyFormat, //将json数据格式化输出
                SerializerFeature.WriteNullStringAsEmpty, //将null值转换为空字符串
                SerializerFeature.WriteNullListAsEmpty, //将空列表转换为空字符串
                SerializerFeature.WriteMapNullValue, //将空map转换为空字符串
                SerializerFeature.MapSortField, //对map的键值对进行排序
                SerializerFeature.DisableCircularReferenceDetect //禁止循环引用
        );
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }
}
